package com.yungu.swift.socket.communication.server.channel.initializer;

import com.yungu.swift.socket.communication.server.handler.WebSocketServerHandler;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.stream.ChunkedWriteHandler;

/**
 * WebSocketChannelInitializer
 *
 * @author cuixiuyin
 * @date 2018/1/6
 */
public class WebSocketChannelInitializer extends ChannelInitializer<SocketChannel> {

    private static final int READ_IDLE_TIME_OUT = 30; // 读超时
    private static final int WRITE_IDLE_TIME_OUT = 0; // 写超时
    private static final int ALL_IDLE_TIME_OUT = 0;  // 所有超时

    @Override
    protected void initChannel(SocketChannel socketChannel) throws Exception {
        socketChannel.pipeline()
                .addLast(new HttpServerCodec())
                .addLast(new HttpObjectAggregator(65536))
                .addLast(new ChunkedWriteHandler())
                //心跳机制的控制 —— 由客户端控制，服务端不做心跳
                //当连接在 30 秒内没有接收到消息时，进会触发一个 IdleStateEvent 事件，被 HeartbeatHandler 的 userEventTriggered 方法处理
                //.addLast(new IdleStateHandler(READ_IDLE_TIME_OUT, WRITE_IDLE_TIME_OUT, ALL_IDLE_TIME_OUT))
                //.addLast(new HearbeatHandler())
                //websocket 处理器
                .addLast(new WebSocketServerHandler());
    }
}
